package com.at;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
//自定义登录用户, 必须实现UserDetailsService
public class UserService implements UserDetailsService {
    //模拟数据库, map里面存放的是用户对象
    static Map<String, com.at.pojo.User> map = new HashMap<String, com.at.pojo.User>();
    static {
        com.at.pojo.User user1 = new com.at.pojo.User();
        user1.setUsername("Sanzhang");
        user1.setPassword("$2a$10$YGXX9kQrM/jwQ6VSMAjMN.u/Jr91sq4ZYVUTD25pR4qLnEqKwzJPe");
        user1.setTelephone("111");

        com.at.pojo.User user2 = new com.at.pojo.User();
        user2.setUsername("Sili");
        user2.setPassword("$2a$10$CpM3VW5yh2vA9l63CSq/N.Hiq9zDerDhzJ3K4Tc4peGgJGbOC5k.y");
        user2.setTelephone("222");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    //loadUserByUsername: 根据用户名加载用户
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*
        根据当前提交过来的用户名, 查询用户对象
        User user = userdao.loadUserByUsername(username);
        */
        com.at.pojo.User user = map.get(username);
        if (user == null) {
            //的那个IQan登录用户没有注册
            return null;
        }
        //获取密码,但是不加密
        String password =user.getPassword();
        //校验用户名, 密码和权限
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("add"));
        list.add(new SimpleGrantedAuthority("delete"));
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return new User(username, password, list);
    }
}
